<script setup lang="ts" name="SystemMyNotify">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { getBoolDictOptions } from '@/utils/dict'
import { DICT_TYPE } from '@/enums/dictEnums'
import { dateTimeFormatter } from '@/utils/dateUtil'
import { MyNotifyApi, MyNotifyType } from '@/api/system/messages/notify/my'
import MyNotifyDetail from './MyNotifyDetail.vue'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const total = ref(0) // 列表的总页数
const list = ref([]) // 表格数据
const queryLoading = ref(false) // 列表加载中：1）列表数据加载；2）查询按钮禁用；3）重置按钮禁用
const queryParams = ref({
  pageIndex: 1,
  pageSize: 20,
  readStatus: undefined,
  create_time: []
})
const queryFormRef = ref() // 搜索的表单
const tableRef = ref() // 表格的 Ref
const selectedIds = ref<number[]>([]) // 表格的选中 ID 数组


/** 查询列表 */
const getList = async () => {
  queryLoading.value = true
  try {
    const data = await MyNotifyApi.page(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    queryLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageIndex = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.pageIndex = 1
  queryParams.value.pageSize = 20
  queryParams.value.readStatus = undefined
  queryParams.value.create_time = []
  tableRef.value.clearSelection()
  handleQuery()
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (data: MyNotifyType) => {
  if (!data.readStatus) {
    handleReadOne(data.id)
  }
  detailRef.value.open(data)
}
/** 标记一条站内信已读 */
const handleReadOne = async (id) => {
  await MyNotifyApi.read(id)
  await getList()
}

/** 标记全部站内信已读 **/
const handleUpdateAll = async () => {
  await MyNotifyApi.allRead()
  message.success(t('sys.messages.notify.my', 'allReadSuccess'))
  tableRef.value.clearSelection()
  await getList()
}

/** 标记一些站内信已读 **/
const handleUpdateList = async () => {
  if (selectedIds.value.length === 0) {
    return
  }
  await MyNotifyApi.read(selectedIds.value)
  message.success(t('sys.messages.notify.my', 'multiplyReadSuccess'))
  tableRef.value.clearSelection()
  await getList()
}

/** 某一行，是否允许选中 */
const selectable = (row) => {
  return !row.readStatus
}

/** 当表格选择项发生变化时会触发该事件  */
const handleSelectionChange = (array: MyNotifyType[]) => {
  selectedIds.value = []
  if (!array) {
    return
  }
  array.forEach((row) => selectedIds.value.push(row.id))
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<template>
  <PageCard>
    <ContentFormTable>
      <template #header>
        <ElForm ref="queryFormRef" :model="queryParams" :inline="true">
          <ElFormItem :label="t('sys.messages.notify.my', 'readStatus')" prop="readStatus">
            <el-select v-model="queryParams.readStatus" class="!w-160px" clearable :placeholder="t('sys.messages.notify.my.rules', 'readStatus')" @change="handleQuery">
              <el-option v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)" :key="dict.label" :label="dict.label" :value="dict.value" />
            </el-select>
          </ElFormItem>
          <ElFormItem :label="t('sys.messages.notify.my', 'sendTime')" prop="create_time">
            <el-date-picker
              v-model="queryParams.create_time"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-240px"
              clearable
              :start-placeholder="t('common', 'startDate')"
              :end-placeholder="t('common', 'endDate')"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleQuery" />
          </ElFormItem>
          <ElFormItem>
            <el-button type="primary" :disabled="queryLoading" icon="Search" @click="handleQuery">{{ t('action',
              'search') }}</el-button>
            <el-button icon="Refresh" :disabled="queryLoading" @click="resetQuery">{{ t('action', 'reset')
            }}</el-button>
          </ElFormItem>
        </ElForm>
      </template>
      <template #tool>
        <div class="tool-body">
          <el-button type="primary" plain size="small" :disabled="selectedIds.length === 0" @click="handleUpdateList"> <SvgIcon icon="ep:reading" class="mr-5px" /> {{ t('sys.messages.notify.my', 'toRead') }} </el-button>
          <el-button type="primary" plain size="small" @click="handleUpdateAll"> <SvgIcon icon="ep:reading" class="mr-5px" /> {{ t('sys.messages.notify.my', 'allRead') }} </el-button>
        </div>
      </template>
      <template #content>
        <el-table ref="tableRef" v-loading="queryLoading && systemConfig.loadingType === 'module'" :data="list" row-key="id" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" :selectable="selectable" :reserve-selection="true" />
          <el-table-column prop="templateNickname" :label="t('sys.messages.notify.my', 'templateNickname')" align="center" />
          <el-table-column prop="create_time" :label="t('sys.messages.notify.my', 'sendTime')" :formatter="dateTimeFormatter" align="center" />
          <el-table-column align="center" :label="t('sys.messages.notify.my', 'templateType')" prop="templateType">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SYSTEM_NOTIFY_TEMPLATE_TYPE" :value="scope.row.templateType" />
            </template>
          </el-table-column>
          <el-table-column :label="t('sys.messages.notify.my', 'templateContent')" align="center" prop="templateContent" show-overflow-tooltip />
          <el-table-column :label="t('sys.messages.notify.my', 'readStatus')" align="center" prop="readStatus" width="160">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.readStatus" />
            </template>
          </el-table-column>
          <el-table-column :label="t('sys.messages.notify.my', 'readTime')" align="center" prop="readTime" width="200" :formatter="dateTimeFormatter" />
          <el-table-column prop="operate" :label="t('common', 'operate')" width="90" align="center" fixed="right">
            <template #default="scope">
              <el-button :type="scope.row.readStatus ? 'primary' : 'warning'" @click="openDetail(scope.row)">{{
                scope.row.readStatus ? t('action', 'detail') : t('sys.messages.notify.my', 'read') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageIndex" :total="total" :disabled="queryLoading" @pagination="getList" />
        <!-- 表单弹窗：详情 -->
        <MyNotifyDetail ref="detailRef" />
      </template>
    </ContentFormTable>
  </PageCard>
</template>

<style scoped lang="scss">
.el-table {
  width: 100%;
  height: 100%;
}

.tool-body{
  display: flex;
  flex: 1;
  padding: 12px;
  background-color: var(--el-fill-color-lighter);
  border: 1px solid var(--el-border-color-light);
  border-bottom: none;
}
</style>
